package service.script;

import org.apache.log4j.Logger;

import communication.MessageHelper;
import communication.ParameterizedMessage;
import communication.ParameterizedMessageImpl;

import scriptrunner.execution.ExecuteErrorException;
import scriptrunner.execution.Function;
import scriptrunner.execution.ValueObject;
import scriptrunner.execution.cloud.CloudFunctionProxy;
import scriptrunner.execution.cloud.CloudResult;
import service.AbstractService;
import service.ServiceRequestHandler;

public class FunctionExecuteRequestHandler  extends ServiceRequestHandler {
	
	private Logger logger = Logger.getLogger(FunctionExecuteRequestHandler.class);

	public FunctionExecuteRequestHandler(AbstractService service) {
		super("ScriptExecutionService::Function::Execute", service);
	}

	@Override
	public ParameterizedMessage handle(ParameterizedMessage message) {
		logger.debug("New function execute request.");
		
		CloudFunctionProxy function = (CloudFunctionProxy) message.getAttachment();
		
		ParameterizedMessage resultMsg = new ParameterizedMessageImpl("Result");
		
		ValueObject result = null;
		try {
			result = function.Execute();
		} catch (ExecuteErrorException e) {
			MessageHelper.markAsFailed(resultMsg, e);
			
			logger.error("Failed to execute function.", e);
			
			return resultMsg;
		}
		
		CloudResult cloudResult = new CloudResult(function.getSession(), result);

		MessageHelper.markAsSuccess(resultMsg, cloudResult);
		
		return resultMsg;
	}

}
